// import mitt from 'mitt';
import { STORAGE } from '@/config';

const STORAGE_TOKEN_KEY = 'storage-token-key';
// 存储和获取token
export const setToken = (token: string) => STORAGE.setItem(STORAGE_TOKEN_KEY, token);
export const getToken = () => STORAGE.getItem(STORAGE_TOKEN_KEY);

// 扁平数据转成树
interface TreeItem {
  id: number;
  pid: number;
  children?: TreeItem[];
}
export function arrayToTree<T extends TreeItem>(arr: T[], pid: number) {
  const result: T[] = [];
  arr.forEach(item => {
    if (item.pid === pid) {
      const itemChildren = arrayToTree(arr, item.id);
      if (itemChildren.length > 0) item.children = itemChildren;
      result.push(item);
    }
  });
  return result;
}
// base64格式转成blob文件对象
export const base64ToBlob = (dataUrl: string) => {
  const arr = dataUrl.split(',');
  const mime = arr[0].match(/:(.*?);/)![1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) u8arr[n] = bstr.charCodeAt(n);
  return new Blob([u8arr], { type: mime });
};

// 驼峰转连字符
export const camelToDash = (str: string) => str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

// 连字符转驼峰
export const dashToCamel = (str: string) => str.replace(/(?:^|-)([a-z])/g, (_, p1) => p1.toUpperCase());

// 事件总线
// 相当于Vue2的const eventBut = new Vue(); eventBut.$on；eventBut.$emit；
// export const emitter = mitt();

// 图片压缩
export const compress = (file: File, limit = 100): Promise<Blob> => new Promise(resolve => {
  const objectURL = URL.createObjectURL(file);
  const img = document.createElement('img');
  img.src = objectURL;
  img.onload = () => {
    // 使用完objectURL之后需要手动释放内存
    URL.revokeObjectURL(objectURL);
    const canvas = document.createElement('canvas');
    // 读取图片的原始宽和高，计算宽高比例
    const ratio = img.naturalWidth / img.naturalHeight;
    let w, h;
    if (ratio >= 1) {
      w = limit;
      h = limit / ratio;
    } else {
      w = limit * ratio;
      h = limit;
    }
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext('2d');
    ctx!.drawImage(img, 0, 0, w, h);
    canvas.toBlob(blob => resolve(blob!));
  };
});

export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));

// 数组根据某个属性去重
export const removeRepeatByKey = <T extends AnyObject>(arr: T[], key: string) => {
  return arr.filter((item, index) => {
    return index === arr.findIndex(jtem => jtem[key] === item[key]);
  });
};
